package com.flyxiaozhu.erp.admin;


import com.flyxiaozhu.erp.core.entities.AdminRole;
import com.flyxiaozhu.erp.core.entities.AdminUser;
import com.flyxiaozhu.erp.core.entities.Role;
import com.flyxiaozhu.erp.core.libs.Constants;
import com.flyxiaozhu.erp.core.repositories.AdminRoleRepository;
import com.flyxiaozhu.erp.core.repositories.AdminUserRepository;
import com.flyxiaozhu.erp.core.repositories.RoleRepository;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class AddAdminUser implements ApplicationRunner {
    @Autowired
    AdminUserRepository adminUserRepository;

    @Autowired
    AdminRoleRepository adminRoleRepository;

    @Autowired
    RoleRepository roleRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        AdminUser adminUser = adminUserRepository.findAdminUserByUsername("admin");
        if (adminUser == null) {
            adminUser = new AdminUser();
            adminUser.setRealname("江死秒");
            adminUser.setPassword(DigestUtils.md5Hex("yy10241905"));
            adminUser.setStatus(Constants.USER_STATUS_NORMAL);
            adminUser.setUsername("admin");
            Long adminUserId = adminUserRepository.save(adminUser).getId();
            System.out.println("============添加用户============");
            System.out.println(adminUser.getRealname());

            Role role = roleRepository.findByName("超级管理员");
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminUserId(adminUserId);
            adminRole.setRoleId(role.getId());

            adminRoleRepository.save(adminRole);
            System.out.println("============添加用户角色============");
            System.out.println("用户：" + adminUser.getRealname() + "，角色：" + role.getName());
        }
    }
}
